package org.agora.photogallery.client.presenter;

import java.util.ArrayList;

import org.agora.photogallery.client.event.GalleryClickedEvent;
import org.agora.photogallery.client.event.GalleryClickedHandler;
import org.agora.photogallery.client.event.PhotoThumbnailClickedEvent;
import org.agora.photogallery.client.model.Gallery;
import org.agora.photogallery.client.model.Photo;
import org.agora.photogallery.client.service.PhotoService;
import org.agora.photogallery.client.view.PhotoCollectionView;

import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;

public class PhotoCollectionPresenter implements Presenter, PhotoCollectionView.PhotoCollectionPresenter, 
			GalleryClickedHandler{
	
	

	private final PhotoCollectionView view;
	private final PhotoService service;
	private final HandlerManager eventBus;
	
	@Inject
	public PhotoCollectionPresenter(PhotoCollectionView view,
			PhotoService service, HandlerManager eventBus) {
		super();
		this.view = view;
		view.setPresenter(this);
		this.service = service;
		this.eventBus = eventBus;
		eventBus.addHandler(GalleryClickedEvent.TYPE,this);
	}
	
	
	@Override
	public void present(HasWidgets container) {
		container.add(view.asWidget());
		
	}

	@Override
	public void onItemClicked(Photo p) {
		eventBus.fireEvent(new PhotoThumbnailClickedEvent(p));
	}


	@Override
	public void onGalleryClicked(GalleryClickedEvent event) {
		Gallery g = event.getGallery();
		loadGallery(g.getId());
		
	}


	public void loadGallery(String id) {
		service.getPhotoesFor(id,new AsyncCallback<ArrayList<Photo>>() {
			@Override
			public void onSuccess(ArrayList<Photo> result) {
				view.setData(result);
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});

		
	}
	

}
